<template>
  <div class="app-container">
    <chat-header/>
    <div class="qr-code-container">
      <el-row :gutter="20">
        <!-- 表单区域 -->
        <el-col :span="12">
          <div class="form-container">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin-top: 20px;">

              <el-row>
                <el-col :span="24">
                  <el-form-item label="样式" prop="qrStyle">
                    <el-select placeholder="请选择..." filterable v-model="form.qrStyle" style="width: 100%;">
                      <el-option
                        v-for="item in this.qrStyleList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if="this.form.qrStyle === 'customize'">
                <el-col :span="24">
                  <el-form-item label="宽" prop="width">
                    <el-tooltip content="设置宽度，范围300-600像素" placement="top">
                      <el-input-number
                        v-model="form.width"
                        controls-position="right"
                        :min="300"
                        :max="600"
                        style="width: 100%;">
                      </el-input-number>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if="this.form.qrStyle === 'customize'">
                <el-col :span="24">
                  <el-form-item label="高" prop="height">
                    <el-tooltip content="设置高度，范围300-600像素" placement="top">
                      <el-input-number
                        v-model="form.height"
                        controls-position="right"
                        :min="300"
                        :max="600"
                        style="width: 100%;">
                      </el-input-number>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if="this.form.qrStyle === 'customize'">
                <el-col :span="24">
                  <el-form-item label="边距" prop="margin">
                    <el-tooltip content="设置二维码与背景的边距，范围3-10像素" placement="top">
                      <el-input-number
                        v-model="form.margin"
                        controls-position="right"
                        :min="3"
                        :max="10"
                        style="width: 100%;">
                      </el-input-number>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if="this.form.qrStyle === 'customize'">
                <el-col :span="24">
                  <el-form-item label="logo路径" prop="imgPath">
                    <el-input v-model="form.imgPath" placeholder="请输入logo文件路径，例：【D:\\logo.png】" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item label="生成方式" prop="generateWay">
                    <el-select placeholder="请选择..." filterable v-model="form.generateWay" style="width: 100%;">
                      <el-option
                        v-for="item in this.generateList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item label="内容" prop="content">
                    <textarea v-model="form.content" placeholder="请输入..." style="width: 100% !important; max-width: 100% !important;  min-width: 100% !important; min-height: 100px !important; max-height: 200px !important;" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if="this.form.generateWay === 'browserDownload'">
                <el-col :span="24">
                  <el-form-item label="文件名称" prop="fileName">
                    <el-input v-model="form.fileName" placeholder="请输入文件名称" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if="this.form.generateWay === 'filePath'">
                <el-col :span="24">
                  <el-form-item label="文件路径" prop="filePath">
                    <div style="display: flex; align-items: center;">
                      <el-dropdown @command="handleSystemPathSelect" style="margin-right: 10px;">
                        <el-button>
                          系统盘<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu>
                          <el-dropdown-item command="C:">C盘</el-dropdown-item>
                          <el-dropdown-item command="D:">D盘</el-dropdown-item>
                          <el-dropdown-item command="E:">E盘</el-dropdown-item>
                          <el-dropdown-item command="F:">F盘</el-dropdown-item>
                          <el-dropdown-item command="G:">G盘</el-dropdown-item>
                          <el-dropdown-item command="H:">H盘</el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                      <el-input v-model="form.filePath" placeholder="请输入文件全路径，例：D:\\cs.png" style="flex: 1;" />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <div class="form-actions">
                    <el-button type="primary" @click="submitForm" icon="el-icon-plus">生 成</el-button>
                    <el-button @click="cancel" icon="el-icon-refresh">重 置</el-button>
                    <el-button v-if="form.content" @click="previewQRCode" type="success" icon="el-icon-view">预 览</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-col>

        <!-- 二维码预览区域 -->
        <el-col :span="12">
          <div class="preview-container">
            <h3>二维码预览</h3>
            <div v-if="qrCodePreview" class="qr-preview">
              <img :src="qrCodePreview" alt="二维码预览" class="qr-image" />
              <div class="preview-info">
                <p><strong>内容:</strong> {{ form.content || '无' }}</p>
                <p><strong>尺寸:</strong> {{ form.width }}x{{ form.height }} 像素</p>
                <el-button @click="downloadPreview" type="primary" size="small">下载预览图</el-button>
              </div>
            </div>
            <div v-else class="no-preview">
              <p>请输入内容并点击"预览"按钮生成二维码</p>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import ChatHeader from "@/components/ai/ChatHeader.vue";
import {generateQRCode} from "@/api/ai/qrCode/qrCode.js";

export default {
  name: "QRCode",
  components:{
    ChatHeader
  },
  data() {
    return {
      // 表单参数
      form: {
        qrStyle: 'default',
        generateWay: 'filePath',
        content: null,
        filePath: null,
        fileName: null,
        isSuffix: null,
        width: 300,
        height: 300,
        margin: 3,
        imgPath: null,
      },
      // 表单校验
      rules: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        filePath: [
          { required: this.form.generateWay === 'filePath', message: "文件路径不能为空", trigger: "blur" }
        ],
        fileName: [
          { required: this.form.generateWay === 'browserDownload', message: "文件名称不能为空", trigger: "blur" }
        ],
      },
      qrStyleList: [
        {
          name: '默认',
          id: 'default'
        },
        {
          name: '青色',
          id: 'cyan'
        },
        {
          name: '自定义',
          id: 'customize'
        },
      ],
      generateList: [
        {
          name: '指定路径',
          id: 'filePath'
        },
        {
          name: '浏览器下载',
          id: 'browserDownload'
        },
      ],
      // 二维码预览数据
      qrCodePreview: null,
    };
  },
  created() {
  },
  computed: {
  },
  methods: {
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.generateWay === 'browserDownload') {
            // 对于浏览器下载，使用API方法并手动触发下载
            this.downloadQRCodeViaAPI();
          } else {
            // 对于保存到路径，使用原来的API调用
            generateQRCode(this.form).then(response => {
              this.$modal.msgSuccess("二维码生成成功");
            }).catch(error => {
              this.$modal.msgError("生成失败: " + (error.message || "未知错误"));
            });
          }
        }
      });
    },
    // 通过API下载二维码
    downloadQRCodeViaAPI: function() {
      // 准备数据
      const requestData = {
        ...this.form,
        isSuffix: this.form.fileName ? this.form.fileName.includes('.') : false
      };

      // 使用API方法
      generateQRCode(requestData).then(response => {
        console.log('响应对象:', response); // 调试信息

        // 检查响应结构
        let blobData;
        if (response && response.data instanceof Blob) {
          blobData = response.data;
        } else if (response instanceof Blob) {
          blobData = response;
        } else {
          this.$modal.msgError("响应数据格式不正确");
          return;
        }

        if (blobData) {
          // 检查是否是错误响应 (JSON格式)
          if (blobData.type === 'application/json' || blobData.type === 'text/plain') {
            const reader = new FileReader();
            reader.onload = () => {
              try {
                const errorData = JSON.parse(reader.result);
                this.$modal.msgError("生成失败: " + (errorData.message || errorData.error || reader.result));
              } catch (e) {
                this.$modal.msgError("生成失败: " + reader.result);
              }
            };
            reader.readAsText(blobData);
            return;
          }

          // 创建下载链接
          const url = window.URL.createObjectURL(blobData);
          const link = document.createElement('a');
          link.href = url;

          // 设置文件名
          let fileName = this.form.fileName || 'qrcode.png';
          if (!fileName.includes('.')) {
            fileName += '.png';
          }

          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
          this.$modal.msgSuccess("二维码下载成功");
        } else {
          this.$modal.msgError("响应数据为空");
        }
      }).catch(error => {
        console.error("下载失败:", error);
        this.$modal.msgError("下载失败: " + (error.message || "未知错误"));
      });
    },
    // 预览二维码
    previewQRCode: function() {
      if (!this.form.content) {
        this.$modal.msgWarning("请输入二维码内容");
        return;
      }

      // 使用在线API生成预览二维码
      const content = encodeURIComponent(this.form.content);
      this.qrCodePreview = `https://api.qrserver.com/v1/create-qr-code/?size=${this.form.width}x${this.form.height}&data=${content}`;
    },
    // 下载预览二维码
    downloadPreview: function() {
      if (this.qrCodePreview) {
        const link = document.createElement('a');
        link.href = this.qrCodePreview;
        let fileName = this.form.fileName || 'qrcode_preview.png';
        if (!fileName.includes('.')) {
          fileName += '.png';
        }
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.$modal.msgSuccess("预览图下载成功");
      }
    },
    // 取消按钮
    cancel() {
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        qrStyle: 'default',
        generateWay: 'filePath',
        content: null,
        filePath: null,
        fileName: null,
        isSuffix: null
      };
      this.qrCodePreview = null;
      this.resetForm("form");
    },
    // 处理系统盘选择
    handleSystemPathSelect(command) {
      this.form.filePath = command + "\\\\";
    },
  },
  watch: {
    // 监听内容变化，清除预览
    'form.content'(newVal) {
      if (!newVal) {
        this.qrCodePreview = null;
      }
    },
    // 监听宽度变化，防止清空
    'form.width': {
      handler(newVal) {
        if (newVal === null || newVal === undefined || newVal === '') {
          this.$nextTick(() => {
            this.form.width = 300;
          });
        }
      },
      immediate: true
    },
    // 监听高度变化，防止清空
    'form.height': {
      handler(newVal) {
        if (newVal === null || newVal === undefined || newVal === '') {
          this.$nextTick(() => {
            this.form.height = 300;
          });
        }
      },
      immediate: true
    },
    // 监听高度变化，防止清空
    'form.margin': {
      handler(newVal) {
        if (newVal === null || newVal === undefined || newVal === '') {
          this.$nextTick(() => {
            this.form.margin = 3;
          });
        }
      },
      immediate: true
    }
  }
};
</script>

<style scoped>
.qr-code-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.form-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
  min-height: 450px;
  display: flex;
  flex-direction: column;
}

.preview-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
  min-height: 450px;
  display: flex;
  flex-direction: column;
}

.preview-container h3 {
  margin-top: 0;
  color: #333;
}

.qr-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.qr-image {
  max-width: 300px;
  max-height: 300px;
  border: 1px solid #ddd;
  padding: 10px;
  margin-bottom: 20px;
}

.preview-info {
  text-align: left;
  width: 100%;
  max-width: 300px;
}

.preview-info p {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
}

.no-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.form-actions {
  text-align: center;
  padding-top: 20px;
}

.form-actions .el-button {
  margin: 0 10px;
}

@media (max-width: 768px) {
  .qr-code-container .el-row {
    flex-direction: column;
  }

  .qr-code-container .el-col {
    width: 100%;
    margin-bottom: 20px;
  }
}
</style>
